import React, { Fragment, useEffect } from 'react';
import { connect } from 'umi';
import { Button, Form, Table, Input, Tag, message } from 'antd';
import moment from 'moment';
import AuthCode from '@/utils/auth/AuthCode';
import authHelpr from '@/utils/auth/helper';
import Pagination from '@/components/Pagination';
import { history } from 'umi';
import request from '@/utils/request';
import { eventTrack } from '@/utils/track';

import styles from '../RulesList.less';

const { checkCode } = authHelpr;

const institutionName = {
    personnel: '人事制度',
    finance: '财务制度'
};

const RulesTable = ({
    dispatch,
    form,
    loading,
    user,
    rulesList,
    institutionType,
    ruleType,
    code,
    nowPage,
    query = {},
    pathname
}) => {
    const { authCode } = new AuthCode(code);

    const { rulesTableList } = rulesList;
    const { getFieldDecorator } = form;
    const User = user.currentUser; // 登陆人信息
    // console.log('================>User', User);

    const getTitle = record => {
        const publishTime = moment(record.publishTime).isBefore(
            moment()
                .subtract(30, 'days')
                .format('YYYY-MM-DD HH:mm:ss')
        );
        const link =
            record.detailPage === 1
                ? '/office/personnelManagement/organization/rank/detail'
                : '/office/institutions/rulesManage/institutionsDetail';
        return (
            <Fragment>
                <div className={styles.titleName}>
                    {publishTime ? '' : <Tag color="red">NEW</Tag>}
                    {checkCode(authCode('detail')) ? (
                        <a
                            className={styles.LinkTo}
                            onClick={() => {
                                eventTrack({
                                    eventName: 'institutions_rules_manage_context_click',
                                    pageName: 'institutions_rules_manage',
                                    eventProps: {
                                        click_context: record.institutionName
                                    }
                                });
                                history.push({
                                    pathname: link,
                                    query: { id: record.id }
                                    // state: { tabRoute: true, tabRefresh: true }
                                });
                            }}
                        >
                            {record.institutionName}
                        </a>
                    ) : (
                        <span title={record.institutionName}>{record.institutionName}</span>
                    )}
                </div>
                <div
                    title={record.institutionIntroduce}
                    className={styles.titleDetail}
                    style={{
                        WebkitBoxOrient: 'vertical'
                    }}
                >
                    {record.institutionIntroduce}
                </div>
            </Fragment>
        );
    };
    const getTime = record => {
        if (record.auditEffectFlag === 'yes' || record.endTime === '') {
            return `${moment(record.publishTime).format('YYYY-MM-DD')} 起`;
        }

        return `${moment(record.startTime).format('YYYY-MM-DD')} 至 ${moment(record.endTime).format('YYYY-MM-DD')}`;

        // if (record.endTime === '') {
        //     return `${moment(record.startTime).format('YYYY-MM-DD')}起`;
        // }
        // return `${moment(record.startTime).format('YYYY-MM-DD')} 至 ${moment(
        //     record.endTime
        // ).format('YYYY-MM-DD')}`;
    };
    const columns = [
        {
            title: '标题',
            width: 220,
            render: (text, record) => getTitle(record)
        },
        {
            title: '实施范围',
            width: 200,
            dataIndex: 'companyName',
            key: 'companyName'
        },
        {
            title: '类型',
            width: 150,
            render: (text, record) =>
                ruleType.map(item => {
                    if (item.dictValue === record.institutionType) {
                        return item.dictName;
                    }
                    return '';
                })
        },
        {
            title: '发布时间',
            width: 150,
            dataIndex: 'publishTime',
            key: 'publishTime'
        },
        {
            title: '生效日期',
            width: 200,
            render: (text, record) => getTime(record)
        }
    ];

    const handleSubmit = (e, type) => {
        if (e) {
            e.preventDefault();
        }
        const { keyword = '' } = form.getFieldsValue();
        dispatch({
            type: 'rulesList/featchList',
            payload: {
                organizationCode: User?.firstOrgInfo?.firstCompanyCode,
                institutionType: institutionType === 'all' ? '' : institutionType,
                keyword,
                pageNo: type === 'reset' ? 1 : rulesTableList[institutionType].pagination.current,
                pageSize: type === 'reset' ? 10 : rulesTableList[institutionType].pagination.pageSize
            },
            callback: res => {
                const obj = {
                    list: res.rows,
                    pagination: {
                        pageSize: res.pageSize,
                        current: res.pageNo,
                        total: res.total
                    }
                };
                rulesTableList[institutionType] = obj;
                dispatch({
                    type: 'rulesList/save',
                    payload: {
                        rulesTableList: { ...rulesTableList }
                    }
                });
            }
        });
    };

    // 表格表头点击切换排序
    const changeTable = async newPagination => {
        rulesTableList[institutionType].pagination = {
            ...rulesTableList[institutionType].pagination,
            ...newPagination
        };
        await dispatch({
            type: 'rulesList/save',
            payload: {
                rulesTableList: { ...rulesTableList }
            }
        });
        const { keyword = '' } = form.getFieldsValue();
        const newQuery = {
            companyId: User.companyId,
            institutionType: institutionType === 'all' ? '' : institutionType,
            keyword,
            pageNo: newPagination.current,
            pageSize: newPagination.pageSize,
            page: nowPage
        };
        history.push({
            pathname,
            query: {
                ...query,
                ...newQuery
            }
        });
        handleSubmit();
    };
    // useEffect(
    //     () => () => {
    //         rulesTableList[institutionType].pagination.pageSize = 10;
    //         rulesTableList[institutionType].pagination.current = 1;
    //         rulesTableList[institutionType].pagination.total = 0;
    //         dispatch({
    //             type: 'rulesList/save',
    //             payload: {
    //                 rulesTableList: { ...rulesTableList }
    //             }
    //         });
    //     },
    //     []
    // );
    // 制度发布申请
    const apply = async () => {
        const response = await request(
            '/api/workflowweb/processinstance/v1/getByAdvancedSettingType?classification=InstitutionApply'
        );
        if (response?.code === 10000) {
            history.push({
                pathname: '/personal/portal/apply',
                query: {
                    id: response?.data?.actProcessDefinitionId,
                    name: response?.data?.processName,
                    institutionName: institutionName[institutionType],
                    institutionType
                }
            });
        } else {
            message.error(response?.msg);
        }
    };
    // 页面刷新时重置页码
    useEffect(() => {
        handleSubmit();
    }, []);
    // tab返回按钮，路由页面参数改变时重新请求
    // useEffect(() => {
    //     handleSubmit(null, 'reset');
    // }, [nowPage]);
    return (
        <Fragment>
            <div className={styles.flexForm}>
                <Form
                    layout="inline"
                    onSubmit={e => {
                        const { keyword = '' } = form.getFieldsValue();
                        const newQuery = {
                            companyId: User.companyId,
                            institutionType: institutionType === 'all' ? '' : institutionType,
                            keyword,
                            pageNo: rulesTableList[institutionType].pagination.current,
                            pageSize: rulesTableList[institutionType].pagination.pageSize,
                            page: nowPage
                        };
                        history.push({
                            pathname,
                            query: {
                                ...query,
                                ...newQuery,
                                page: nowPage
                            }
                        });
                        handleSubmit(e, 'reset');
                    }}
                >
                    <Form.Item>
                        {getFieldDecorator('keyword', {
                            initialValue: query.keyword
                        })(
                            <Input
                                onClick={() => {
                                    eventTrack({
                                        eventName: 'institutions_rules_manage_search_input_click',
                                        pageName: 'institutions_rules_manage'
                                    });
                                }}
                                placeholder="请输入标题或关键字"
                                style={{ width: 260 }}
                                allowClear
                            />
                        )}
                    </Form.Item>
                    <Form.Item>
                        <Button
                            type="primary"
                            htmlType="submit"
                            onClick={() => {
                                eventTrack({
                                    eventName: 'institutions_rules_manage_search_submit_click',
                                    pageName: 'institutions_rules_manage',
                                    eventProps: {
                                        submit_context: form.getFieldValue('keyword')
                                    }
                                });
                            }}
                        >
                            搜索
                        </Button>
                    </Form.Item>
                </Form>
                <div className={styles.rightButton}>
                    {checkCode(authCode('save')) ? (
                        <Button
                            type="primary"
                            onClick={() => {
                                apply();
                                eventTrack({
                                    eventName: 'institutions_rules_manage_search_submit_click',
                                    pageName: 'institutions_rules_manage'
                                });
                            }}
                        >
                            制度发布申请
                        </Button>
                    ) : (
                        ''
                    )}
                </div>
            </div>

            <Table
                loading={loading.effects['rulesList/featchList']}
                dataSource={rulesTableList[institutionType].list}
                columns={columns}
                scroll={{ x: 'max-content' }}
                onChange={changeTable}
                rowKey="id"
                pagination={false}
            />
            <Pagination {...rulesTableList[institutionType].pagination} onChange={changeTable}></Pagination>
        </Fragment>
    );
};
export default connect(({ loading, rulesList, user }) => ({
    loading,
    rulesList,
    user
}))(Form.create()(RulesTable));
